<template>
  <div class="app-container" style="font-size: 14px;font-weight: 500">
    <div class="filter-container">
      <el-form :inline="true" :model="form" ref="ruleFormRef" :rules="formRule" class="area-inline">
        <el-form-item label="任务名称" prop="title" class="input">
          <el-input v-model="form.title" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="国家" prop="country_code" class="input">
          <el-select ref="selectOption" v-model="value" clearable filterable placeholder="请选择国家"
                     style="width: 300px"
                     @change="countryHandleChange">
            <el-option
                style="width: 300px"
                v-for="item in options"
                :key="item.country_id"
                :label="item.name"
                :value="{label:item.name,value:item.country_id}"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据来源" prop="type" class="input">
          <el-radio-group v-model="form.type" @click="radioClick">
            <el-radio label="10">上传文档</el-radio>
            <el-radio label="20">生成号码</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.title !='' && form.country_code != '' && form.type == '10'" class="flex align-center">
          <el-upload
              ref="upload"
              class="upload-demo"
              action=""
              accept=".txt"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :http-request="handleHttpRequest"
              :limit="1"
              :file-list="fileList"
              :on-change="uploadHandleChange">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">仅支持txt文件，且小于10M</div>
            <el-progress v-show="showProcess" :percentage="processLength"  status="success" :stroke-width="2"/>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="form.type == '20'" class="input">
          <el-select ref="selectOption" v-model="form.gen_task_id" clearable filterable placeholder="请选择号码生成任务"
                     style="width: 300px"
                     @change="genHandleChange">
            <el-option
                style="width: 300px"
                v-for="item in genOptions"
                :key="item.id"
                :label="item.title"
                :value="{label:item.total_number,value:item.id}">
              >
              <span style="float: left">{{ item.title }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.country_city }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" v-if="form.title !='' && form.country_code != ''"
                     @click="handleAddTable">添加筛选
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="tit_btn">
      <div style="font-size: 16px;font-weight: bolder">任务明细</div>
      <div style="display: flex;position:absolute;right:20px">
        <template v-if="multipleSelection.length>0">
          <el-button type="success" size="small" @click="handleBatchDelete">删除</el-button>
          <el-button type="success" size="small" @click="handleCreate">筛选开通</el-button>
        </template>
      </div>
    </div>
    <el-table
        ref="multipleTable"
        :data="list"
        border
        fit
        size="medium"
        highlight-current-row
        @selection-change="handleSelectionChange"
        style="margin-top: 20px"
    >

      <el-table-column type="selection" align="center"/>
      <el-table-column label="序号" prop="index" width="55">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务名称">
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column label="国家">
        <template slot-scope="scope">
          {{ scope.row.country_name }}
        </template>
      </el-table-column>
      <el-table-column prop="type" label="数据来源" :formatter="typeFormat" width="150"/>
      <el-table-column label="总号数">
        <template slot-scope="scope">
          {{ scope.row.number_count }}
        </template>
      </el-table-column>
      <el-table-column label="消耗积分">
        <template slot-scope="scope">
          {{ scope.row.totalPrice }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <template>
            <el-button type="primary" size="mini" @click="screenHandle(row,$index)">
              筛选
            </el-button>
            <el-button type="primary" size="mini" @click="handleDelete(row,$index)">
              删除
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import {getGenerateCountry, genCreate, genList} from '@/api/generate'
import {taskFiltrate} from '@/api/whats'
import splitPane from 'vue-splitpane'
import {create} from "@/api/user";
import {upload} from "@/api/upload";

let id = 0;
export default {
  inject: ['reload'],
  components: {splitPane},
  data() {
    return {
      loading: false,
      value: [],
      options: [],
      genOptions: [],
      props: {
        disabled: true
      },
      list: [],
      multipleSelection: [],
      dialogFormVisible: false,
      form: {
        title: "",
        country_id: "",
        country_name: "",
        file_id: "",
        file_name: "",
        type: "10",
        gen_task_id: "",
        number_count: 0,
        totalCount: 0,
        project: 'whatsapp'
      },
      formRule: {
        title: [{required: true, message: "请输入任务名称", trigger: "blur"}],
        country_id: [{required: true, message: "请选择国家", trigger: "change"}],
        type: [{required: true, message: "请选择数据来源", trigger: "change"}]
      },
      fileList: [],
      processLength: 0,
      showProcess: false,
    }
  },
  created() {
    this.getUserCountryCodeList()
    this.getGenList()
  },
  methods: {
    resize() {
      console.log('resize')
    },
    radioClick() {
      this.form.number_count = 0
      this.form.totalCount = 0
      this.form.file_id = 0
      this.form.file_name = 0
    },
    typeFormat(row, column, cellValue, index) {
      return {10: '上传文档', 20: '生成号码任务'}[cellValue]
    },
    handleRemove() {
      this.form.file_name = ''
      this.form.file_id = 0
      this.form.number_count = 0
      this.fileList = []
    },
    // 上传前处理
    beforeUpload(file) {
      this.fileList = []
      const fileSize = file.size
      const FIVE_M = 30 * 1024 * 1024
      if (fileSize > FIVE_M) {
        this.$message.error(this.$t('message.max'))
        return false
      }
      const fileName = file.name
      const reg = /^.+(\.txt)$/
      if (!reg.test(fileName)) {
        this.$message.error(this.$t('message.type'))
        return false
      }
      return true
    },
    handleHttpRequest(item) {
      const formData = new FormData()
      formData.append('file', item.file)
      formData.append('path', 10)
      upload(formData).then(res => {
        if (res.data.errorCount > 0) {
          this.$refs.upload.clearFiles()
          this.$message.error(this.$t('message.errorCount'))
          return
        }
        this.form.file_name = res.data.fileName
        this.form.file_id = res.data.fileId
        this.form.number_count = res.data.numbers
        this.fileList.push({
          name: res.data.fileName,
          file: item.file
        })
        this.processLength = 100
        this.showProcess = false
        this.$message.success(this.$t('message.uploadSuccess'))
      }).catch(err => {
        this.$refs.upload.clearFiles()
        this.$message.error(err)
      })
    },
    uploadHandleChange(file, fileList) {
      if (file.status === 'ready') {
        this.processLength = 0
        this.showProcess = true
        const interval = setInterval(() => {
          if (this.processLength >= 99) {
            clearInterval(interval)
            return
          }
          this.processLength += 1
        }, 20)
      }

      if (file.status === 'success') {
        this.processLength = 0
        this.showProcess = false
      }
    },
    getGenList() {
      genList().then(response => {
        this.genOptions = response.data.list
      })
    },
    getUserCountryCodeList() {
      getGenerateCountry().then(response => {
        this.options = response.data
      })
    },
    /**添加到table*/
    handleAddTable() {
      if (this.form.type == 10 && !this.form.file_id) {
        this.$message.error('请上传文件')
        return
      }
      if (this.form.type == 20 && !this.form.gen_task_id) {
        this.$message.error('请上选择号码生成任务')
        return
      }

      const data = []
      data['title'] = this.form.title
      data['type'] = this.form.type
      data['number_count'] = this.form.number_count
      data['totalPrice'] = this.form.totalPrice
      data['country_id'] = this.form.country_id
      data['gen_task_id'] = this.form.gen_task_id
      data['file_id'] = this.form.file_id
      data['country_name'] = this.form.country_name
      this.list.push(data)

      this.form.number_count = 0
      this.form.totalCount = 0
      this.form.file_id = 0
      this.form.file_name = 0
      this.fileList = []
    },
    countryHandleChange(params) {
      const {label, value} = params
      this.form.country_name = label
      this.form.country_id = value
    },
    genHandleChange(params) {
      const {label, value} = params
      this.form.number_count = label
      this.form.gen_task_id = value
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleDelete(row, index) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },

    handleBatchDelete() {
      var d = this.list;
      this.$refs.multipleTable.selection.forEach((Ele, index) => {
        //console.log(Ele.date);
        for (var i = 0; i < d.length; i++) {
          var t = d[i].id;
          if (t == Ele.id) {
            d.splice(i, 1);
          }
        }
      });
    },

    /**单行提交赛选*/
    screenHandle(row, index) {
      const params = [{
        'title': row.title,
        'file_id': row.file_id,
        'type': row.type,
        'country_id': row.country_id,
        'project': this.form.project,
        'gen_task_id': row.gen_task_id,
        'filter_type': 0,
      }]
      taskFiltrate({'params': params}).then(res => {
        this.$confirm('Create successful！', 'title', {
          confirmButtonText: 'confirm',
          showCancelButton: false,
          type: 'success'
        }).then(() => {
          this.$router.push({'name': 'whatsappFiltrateList'})
        })
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 多个提交*/
    handleCreate() {
      const params = []
      this.multipleSelection.forEach((item) => {
        const data = {}
        data.title = item.title;
        data.file_id = item.file_id;
        data.type = item.type;
        data.country_id = item.country_id;
        data.project = this.form.project;
        data.gen_task_id = item.gen_task_id;
        data.filter_type = 0;
        params.push(data)
      })
      taskFiltrate({'params': params}).then(res => {
        this.$confirm('Create successful！', 'title', {
          confirmButtonText: 'confirm',
          showCancelButton: false,
          type: 'success'
        }).then(() => {
          this.$router.push({'name': 'whatsappFiltrateList'})
        })
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
  }
}
</script>


<style>
.tit_btn {
  margin: 15px 20px;
  display: flex;
  align-items: center;
}
</style>
